package com.infra.common.util;

import com.infra.common.enums.ChecksumEnum;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 校验工具类
 * 内容校验，常用于计算文件的HASH值（SHA/MD5）
 *
 * @author PD
 */
public class ChecksumUtils {

    public static String getValue(byte[] bytes, ChecksumEnum checksumEnum) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(checksumEnum.getMessage());
        md.update(bytes);

        StringBuffer buf = new StringBuffer();
        byte[] bits = md.digest();
        for (int i = 0; i < bits.length; i++) {
            int a = bits[i];
            if (a < 0) a += 256;
            if (a < 16) buf.append("0");
            buf.append(Integer.toHexString(a));
        }

        return buf.toString();

    }

    /**
     * 获取字符串的总和检验码，校验和
     *
     * @param input        字符数据
     * @param checksumEnum MD5,SHA1值
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getValue(String input, ChecksumEnum checksumEnum) throws NoSuchAlgorithmException {
        return getValue(input.getBytes(), checksumEnum);
    }
}